package edu.sfsu.powerrangers.jeopardy.server;

import java.io.File;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import edu.sfsu.powerrangers.jeopardy.gamestate.Game;

public class ServerApplication {
	public static void main(String[] args) throws RemoteException {
		File gameFile = new File("Games");
		String rmiName = "wtq";
		boolean exit = false;
		for (int i = 0; i < args.length;) {
			String arg = args[i++];
			if ((arg.equals("-g") || arg.equals("-game") || arg.equals("--game")) && i < args.length) {
				gameFile = new File(args[i++]);
			}
			else if ((arg.equals("-n") || arg.equals("-name") || arg.equals("--name")) && i < args.length) {
				rmiName = args[i++];
			}
			else if (arg.equals("-h") || arg.equals("-help") || arg.equals("--help")) {
				System.out.println("Usage: ServerApplication [-g <filename>] [-n <string>] [-h] [-v]");
				System.out.println(" -g <gamefile>    Read games from the specified file or directory.");
				System.out.println("                  Default is \"Games\".");
				System.out.println(" -n <string>      Bind to the specified name in the RMI registry.");
				System.out.println("                  Default is \"wtq\".");
				System.out.println(" -h               Print options.");
				System.out.println(" -v               Print version number.");
				exit = true;
			}
			else if (arg.equals("-v") || arg.equals("-version") || arg.equals("--version")) {
				System.out.println("WhatTheQ Server Version 1.0");
				System.out.println("(c) 2011 Rebecca Bettencourt, Sara McCutcheon, Kenneth Nguyen, Howard Wong");
				exit = true;
			}
			else {
				System.out.println("Usage: ServerApplication [-g <filename>] [-n <string>] [-h] [-v]");
				exit = true;
			}
		}
		if (exit) return;
		System.out.println("WhatTheQ Server Version 1.0");
		System.out.println("(c) 2011 Rebecca Bettencourt, Sara McCutcheon, Kenneth Nguyen, Howard Wong");
		System.out.println("Reading games from: " + gameFile.getAbsolutePath());
		System.out.println("Binding to RMI name: " + rmiName);
		System.out.println("================================================================================");
		
		System.out.println("reading game files...");
		GameReader reader = new GameReader();
		Game[] games = reader.readGames(gameFile);
		
		System.out.println("initializing server controller...");
		ServerController controller = new ServerController(games);
		
		System.out.println("registering with RMI...");
		Remote stub = UnicastRemoteObject.exportObject(controller, 0);
		Registry registry = LocateRegistry.getRegistry();
		registry.rebind(rmiName, stub);
		
		System.out.println(ServerState.WAITING_FOR_CONNECTION.getDescription());
	}
}
